package controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import dao.TeamDao;
import dao.impl.TeamDaoImpl;
import model.JoinTeamMsg2;
import model.Team;
import service.RaceService;
import service.TeamService;
import service.UserService;
import service.impl.RaceServiceImpl;
import service.impl.TeamServiceImpl;
import service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author CY
 * @date 2023/01/03 17:27
 **/
@WebServlet("/teamListByUser")
public class TeamListByUserServlet extends HttpServlet {
    TeamService service = new TeamServiceImpl();
    UserService userService = new UserServiceImpl();
    RaceService raceService = new RaceServiceImpl();
    TeamDao teamDao = new TeamDaoImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf-8");
        //Json解析
        final BufferedReader bufferedReader = new BufferedReader(req.getReader());
        String line = null;
        final StringBuilder json = new StringBuilder();
        while ((line = bufferedReader.readLine()) != null) {
            json.append(line);
        }
        final JSONObject jsonObject = JSON.parseObject(json.toString());
        int uid = Integer.parseInt(jsonObject.getString("uid"));
        int pageIndex = Integer.parseInt(jsonObject.getString("pageIndex"));
        int pageSize = 5;


        //处理请求
//        int count = service.countTeamByUser(uid);
//        System.out.println(count);
        List<Team> teams = service.getTeamByUser(uid, pageIndex, pageSize);
        int count = teams.size();

        List<JoinTeamMsg2> teamMsg = new ArrayList<>();
        for (Team team : teams) {
            final JoinTeamMsg2 joinTeamMsg2 = new JoinTeamMsg2();
            joinTeamMsg2.setTeam(team);
            joinTeamMsg2.setRace(teamDao.raceByTid((int) team.getTid()));
            joinTeamMsg2.setLeader(userService.findById((int) team.getLid()));
            teamMsg.add(joinTeamMsg2);
        }
        System.out.println(teamMsg);

        //返回请求
        JSONObject message = new JSONObject();
        message.put("status", "1");
        message.put("count", count % pageSize != 0 ? count / pageSize + 1 : count / pageSize);
        message.put("teamMsg", teamMsg);
        resp.getWriter().write(message.toString());
    }
}
